package pack.help;

import gnu.io.*;
import java.io.*;
import java.util.*;

import pack.model.Master;
import pack.model.RealRobot;

public class Serial {
	    @SuppressWarnings("rawtypes")
		Enumeration	      portList;
	    CommPortIdentifier portId;
    	BufferedWriter out;
	    SerialPort	      serialPort;
	    OutputStream       outputStream;
	    public InputStream       inputStream;
	    boolean	      outputBufferEmptyFlag = false;
	    int cnt;
	    
	    
	    
	    // THIS BOOLEAN TOGGLES ONLINE/OFFLINE MODE
	    private static boolean online = false;
	    // ****************************
	    
	    RealRobot realRobot;
	    
	    public Serial(String pname){
	    	init_port(pname);
	    	cnt = 0;
	    }
	    
	    /**
		 * The USB interface sends a READY string
		 * when both motors have been stopped,
		 * this method waits for this event
		 * so we can sync with the robot.
		 */
		public void waitForReady(){
			if (online){
				String ans = "";
				int tmp;
				while(!ans.contains("READY")){
					try {
						tmp = inputStream.read();
						if(tmp!=-1){
							System.out.print((char)tmp);
							ans += (char)tmp;
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				System.out.println();
				//cnt++;
				//System.out.println("READY " + ans + cnt);
			} else {
				
				//////////////////////////
				// OFFLINE READY!
				//////////////////////////
				// check ready flag in while()
				//while(!realRobot.pingCmd());
				
				
				
				
				Thread.currentThread();
				try {
					Thread.sleep(Master.sleepfor);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("offline READY");	
					
			}
		}
		
	    
	    public void init_port(String portname) {
	    	if ( online ) {
				boolean portFound = false;
				
				
				String  defaultPort = portname;
				
				
				portList = CommPortIdentifier.getPortIdentifiers();
		
				while (portList.hasMoreElements()) {
				    portId = (CommPortIdentifier) portList.nextElement();
		
				    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				    	System.out.println(portId.getName());
					if (portId.getName().equals(defaultPort)) {
					    System.out.println("Found port " + defaultPort);
		
					    portFound = true;
		
					    try {
						serialPort = 
						    (SerialPort) portId.open("SimpleWrite", 2000);
					    } catch (PortInUseException e) {
						System.out.println("Port in use.");
		
						continue;
					    } 
		
					    try {
					    out = new BufferedWriter(new FileWriter("outfile"));
						outputStream = serialPort.getOutputStream();
						inputStream = serialPort.getInputStream();
					    } catch (IOException e) {}
		
					    try {
						serialPort.setSerialPortParams(115200, 
									       SerialPort.DATABITS_8, 
									       SerialPort.STOPBITS_1, 
									       SerialPort.PARITY_NONE);
					    } catch (UnsupportedCommOperationException e) {}
				
		
					    try {
					    	serialPort.notifyOnOutputEmpty(true);
					    } catch (Exception e) 
						    {
							System.out.println("Error setting event notification");
							System.out.println(e.toString());
							System.exit(-1);
						    }
					  
						    
						    
						}
				    }
					    
				} 
	
				if (!portFound) {
				    System.out.println("port " + defaultPort + " not found.");
				} 
	    	} else {
	    		//realRobot = Main.getRealRobot();
	    		System.out.println("Offline Mode");
	    	}
	    } 
	    
	    public void write(String out){
	    	if (online) {
		    	try {		    	
			        
		    		outputStream.write(out.getBytes());
		    		outputStream.write('\n');
		    		if (!out.contains("run")){
		    			System.out.println(out);
		    		}
		    		
			    } catch (Exception e) {
			    	//
			    	System.out.println("HIBA: "+e.getMessage());
			    }
	    	} else {
	    		if (out.substring(0, 3).equals("pin")){
	    			System.out.println(out);
	    			//if (realRobot.pingCmd()){
	    				//return;
	    		//	}
	    		} else {
	    			//RobotCommand rCmd = new RobotCommand(out);
	    			//realRobot.runCmd(rCmd);
	    		}
	    		// WRITE TO REAL ROBOT
	    			// IF PING -> GETREADY()
	    			// IF CMD  -> apply cmd and then GIVECMD()
	    		    // IF RESET
	    			// IF STOP
	    		//
	    	}
	    }
	    public void closeport(){
	    	if (online) {
		    	try {
				       Thread.sleep(2000);
				       out.close();// Be sure data is xferred before closing
				    } catch (Exception e) {}
				    serialPort.close();
				    System.out.println("Port Closed.");
	    	} else {
	    		System.out.println("Offline Port Closed.");
	    	}
	    }

		public boolean getOnline() {
			return online;
		}
}
